<template>
	<div>
		<div class="wrap">
			<h2>{{ title }}</h2>
			<div class="content">
				<el-form ref="userForm" :model="dialogForm" label-width="130px" :rules="rules">
					<h3>账号信息</h3>
					<el-form-item :label="$t('table.user name')" prop="account">
						<el-input v-model.trim="dialogForm.account" :disabled="id != ''"></el-input>
					</el-form-item>
					<el-form-item :label="$t('login.password')" prop="password">
						<el-input v-model.trim="dialogForm.password" :disabled="id != ''">
							<template slot="append">
								<el-button @click="createPassword">{{ $t('user.random') }}</el-button>
							</template>
						</el-input>
					</el-form-item>
					<el-form-item :label="$t('user.email')" prop="email">
						<el-input v-model="dialogForm.email"></el-input>
						<div class="form-tips font-grey">
							{{ $t('user.createAccountText1') }}
						</div>
					</el-form-item>
					<h3>客户信息</h3>
					<el-form-item :label="$t('user.客户全称')">
						<el-input v-model.trim="dialogForm.customer_name"></el-input>
					</el-form-item>
					<el-form-item :label="$t('user.负责人')">
						<el-input v-model.trim="dialogForm.customer_charge"></el-input>
					</el-form-item>
					<el-form-item :label="$t('user.联系电话')">
						<el-input v-model.trim="dialogForm.customer_phone"></el-input>
					</el-form-item>
					<el-form-item :label="$t('user.公司地址')">
						<el-input v-model.trim="dialogForm.customer_address"></el-input>
					</el-form-item>
					<el-form-item :label="$t('user.客户类型')">
						<el-radio v-model="dialogForm.customer_type" label="1">一般客户</el-radio>
						<el-radio v-model="dialogForm.customer_type" label="2">直客</el-radio>
						<el-radio v-model="dialogForm.customer_type" label="3">同行</el-radio>
					</el-form-item>
					<el-form-item :label="$t('user.结算方式')">
						<el-radio v-model="dialogForm.customer_pay_method" label="1">现金</el-radio>
						<el-radio v-model="dialogForm.customer_pay_method" label="2">周结</el-radio>
						<el-radio v-model="dialogForm.customer_pay_method" label="3">月结</el-radio>
						<el-radio v-model="dialogForm.customer_pay_method" label="4">60天结</el-radio>
						<el-radio v-model="dialogForm.customer_pay_method" label="5">到仓结</el-radio>
					</el-form-item>
					<el-form-item :label="$t('user.销售员')">
						<el-select v-model="dialogForm.customer_sale" placeholder="请选择">
							<el-option v-for="item in empolyeSList" :key="item.id" :label="item.account" :value="item.id"></el-option>
						</el-select>
					</el-form-item>
					<el-form-item :label="$t('user.港前客服')">
						<el-select v-model="dialogForm.customer_service" placeholder="请选择">
							<el-option v-for="item in empolyeCList" :key="item.id" :label="item.account" :value="item.id"></el-option>
						</el-select>
					</el-form-item>
					<el-form-item :label="$t('user.客户档案')">
						<el-upload
							class="upload-demo"
							:action="uploadUrl"
							:headers="uploadHeader"
							:on-preview="handlePreview"
							:on-success="handleSuccess"
							:file-list="fileList"
							:before-upload="beforeUpload"
						>
							<el-button size="small" type="primary">点击上传</el-button>
							<!-- <div slot="tip" class="el-upload__tip">只能上传excel文件，且不超过500kb</div> -->
						</el-upload>
					</el-form-item>

					<h3>权限信息</h3>
					<el-form-item :label="$t('一件代发权限')" prop="oneShippingAdminId">
						<el-select v-model="dialogForm.oneShippingAdminId" placeholder="点击选择运营账户" :disabled="id != ''">
							<el-option v-for="item in oneShippingAdminList" :key="item.adminId" :label="item.account" :value="item.adminId"></el-option>
						</el-select>
					</el-form-item>
					<el-form-item :label="$t('中转送仓权限')" prop="middleTransferAdminId">
						<el-select v-model="dialogForm.middleTransferAdminId" placeholder="点击选择运营账户" :disabled="id != ''">
							<el-option v-for="item in middleTransferAdminList" :key="item.adminId" :label="item.account" :value="item.adminId"></el-option>
						</el-select>
					</el-form-item>
					<el-form-item label="入库分拣权限" prop="inboundSortingAdminId">
						<el-select v-model="dialogForm.inboundSortingAdminId" placeholder="点击选择运营账户" :disabled="id != ''">
							<el-option v-for="item in inboundSortingAdminList" :key="item.adminId" :label="item.account" :value="item.adminId"></el-option>
						</el-select>
					</el-form-item>
				</el-form>
			</div>
		</div>
		<div class="footer">
			<el-button @click="$router.go(-1)">{{ $t('common.back') }}</el-button>
			<el-button @click="createUser" :loading="userLoading" type="primary">{{ $t('common.confirm') }}</el-button>
		</div>
	</div>
</template>

<script>
import { generateRandomString, getFalabellaName, getMercadoName, isEmail } from '@/utils';
import request from '@/utils/request';
import { createUser, getUserList, getEmpolye, getUserInfo, editUserInfo } from '@/api/user';
import { getAllAdmin } from '@/api/admin';
import { ROLE_INBOUND_SORTING, ROLE_MIDDLE_TRANSFER, ROLE_ONE_SHIPPING, ROLE_OPERATE } from '@/utils/admin';
import { getToken } from '@/utils/auth';
export default {
	name: 'addUser',
	computed: {
		oneShippingAdminList() {
			return this.adminList.filter((item) => {
				return item.roles.indexOf(ROLE_ONE_SHIPPING) !== -1;
			});
		},
		middleTransferAdminList() {
			return this.adminList.filter((item) => {
				return item.roles.indexOf(ROLE_MIDDLE_TRANSFER) !== -1;
			});
		},
		inboundSortingAdminList() {
			return this.adminList.filter((item) => {
				return item.roles.indexOf(ROLE_INBOUND_SORTING) !== -1;
			});
		}
	},
	data() {
		const checkEmail = (rule, value, callback) => {
			request({
				url: '/user/checkEmail',
				method: 'get',
				params: this.dialogForm,
				handleError: true
			}).then((res) => {
				if (res.error !== 0) {
					callback(new Error(res.message));
				} else {
					callback();
				}
			});
		};

		const checkAccount = (rule, value, callback) => {
			request({
				url: '/user/checkAccount',
				method: 'get',
				params: this.dialogForm,
				handleError: true
			}).then((res) => {
				if (res.error !== 0) {
					callback(new Error(res.message));
				} else {
					callback();
				}
			});
		};

		return {
			title: '创建账号',
			queryParams: {
				page: 1,
				pageSize: 20,
				accountType: '',
				status: '',
				adminId: '',
				tabType: '',
				platformType: ''
			},
			data: [],
			loading: false,
			userLoading: false,
			total: 0,
			platformTypeList: [],
			userDialog: false,
			is_search: false,
			sortOrders: ['descending', 'ascending', null],
			dialogForm: {
				account: '',
				password: '',
				email: '',
				oneShippingAdminId: '',
				middleTransferAdminId: '',
				inboundSortingAdminId: '',
				customer_url: '',
				file_name: '',
				customer_name: '',
				customer_charge: '',
				customer_phone: '',
				customer_address: '',
				customer_type: '1',
				customer_pay_method: '1',
				customer_sale: '',
				customer_service: ''
			},
			id: '',
			adminList: [],
			rules: {
				account: [
					{ required: true, message: this.$t('common.pleaseFillIn'), trigger: 'blur' },
					{ message: this.$t('user.userValid1'), trigger: 'blur', min: 3 },
					{ message: this.$t('user.userValid2'), trigger: 'blur', max: 20 },
					{ pattern: /^[\u4e00-\u9fa5a-zA-Z0-9_]+$/, message: this.$t('user.userValid3'), trigger: 'blur' },
					{ validator: checkAccount, trigger: 'blur' }
				],
				password: [
					{ required: true, message: this.$t('user.userValid4'), trigger: 'blur', min: 6 },
					{ required: true, message: this.$t('user.userValid4'), trigger: 'change', min: 6 },
					{ message: this.$t('user.userValid5'), trigger: 'blur', max: 30 }
				],
				email: [
					// { required: true, message: this.$t('common.pleaseFillIn') ,trigger: 'blur' }, // 校验邮箱格式
					{ pattern: /^(\w-*\.*)+@(\w-?)+(\.\w{2,})+$/, message: this.$t('user.userValid6'), trigger: 'blur' },
					{ validator: checkEmail, trigger: 'blur' } // 校验邮箱格式
				],
				oneShippingAdminId: [{ required: true, message: this.$t('common.请选择'), trigger: 'change' }],
				middleTransferAdminId: [{ required: true, message: this.$t('common.请选择'), trigger: 'change' }],
				inboundSortingAdminId: [{ required: true, message: this.$t('common.请选择'), trigger: 'change' }]
			},
			fileList: [],
			uploadUrl: process.env.VUE_APP_BASE_API + '/user/uploadFile',
			uploadHeader: {
				Authorization: 'Bearer ' + getToken()
			},
			empolyeCList: [],
			empolyeSList: []
		};
		// /^(\w-*\.*)+@(\w-?)+(\.\w{2,})+$/
	},
	created() {
		if (this.$route.name === 'invalidUserList') {
			this.queryParams.tabType = 'invalid';
		} else if (this.$route.name === 'normalUserList') {
			this.queryParams.tabType = 'normal';
		}
		if (this.$route.query.id) {
			this.id = this.$route.query.id;
			this.getData();
			this.title = '修改账号';
		} else {
			this.id = '';
		}
		this.getEmpolye();
		this.getAdminList();
	},

	updated() {
		// this.$nextTick(() => {
		//   this.$refs['tableData'].doLayout();
		// });
	},
	methods: {
		getFalabellaName,
		getMercadoName,
		getData() {
			this.loading = true;
			getUserInfo(this.id).then((res) => {
				this.loading = false;
				this.dialogForm = res.data;
				if (res.data.file.length != 0) {
					this.fileList.push(res.data.file);
				}
				// this.total = res.info.total;
				// this.platformTypeList = res.info.platformTypeList;
			});
		},
		handlePreview(file) {
			window.open(file.url, '_blank');
		},
		handleSuccess(res, file) {
			if (res.error == 0) {
				this.fileList = [{ url: res.info.imageUrl, name: file.name }];
				this.dialogForm.customer_url = res.info.imageUrl;
				this.dialogForm.file_name = file.name;
			} else {
				this.$errorMessage(res.message);
			}
		},
		beforeUpload(file) {
			const isLt10M = file.size / 1024 / 1024 < 10;
			if (!isLt10M) {
				this.$errorMessage('上传文件大小不能超过 10MB!');
			}
			return isLt10M;
		},

		getEmpolye() {
			//客服
			getEmpolye({
				pageSize: 100,
				job: 'customerservice'
			}).then((res) => {
				this.empolyeCList = res.data;
			});
			//销售
			getEmpolye({
				pageSize: 100,
				job: 'salesperson'
			}).then((res) => {
				this.empolyeSList = res.data;
			});
		},
		getAdminList() {
			getAllAdmin().then((res) => {
				this.adminList = res.data;
				this.showUserDialog();
			});
		},
		// 生成随机密码
		createPassword() {
			this.dialogForm.password = generateRandomString();
		},
		// 创建用户
		createUser() {
			if (this.id) {
				editUserInfo(this.dialogForm).then((res) => {
					this.userLoading = false;
					if (res.error === 0) {
						this.$successMessage(res.message);

						this.resetForm();
						// this.getData(); // 重新请求数据/
						window.location.reload();
					} else {
						this.$errorMessage(res.message);
					}
				});
			} else {
				this.$refs.userForm.validate((valid) => {
					if (valid) {
						this.userLoading = true;
						createUser(this.dialogForm).then((res) => {
							this.userLoading = false;
							if (res.error === 0) {
								this.$successMessage(res.message);

								this.resetForm();
								// this.getData(); // 重新请求数据
								this.$router.push({
									name: 'userList',
									query: {}
								});
							} else {
								this.$errorMessage(res.message);
							}
						});
					}
				});
			}
		},
		// 重置表单
		resetForm() {
			this.dialogForm.password = '';
			this.dialogForm.account = '';
			this.dialogForm.email = '';
		},
		changeOption(is_search = false, type = '') {
			if (is_search == true) {
				//判断是否使用过搜索按钮
				this.is_search = true;
			}
			if (type == 'clear') {
				if (this.is_search == false) {
					return;
				} else {
					this.is_search = false;
				}
			}

			this.queryParams.page = 1;
			this.getData();
		},
		//排序
		handleSortChange(column) {
			this.queryParams.orderBy = '';
			this.queryParams.orderField = '';
			if (column.order) {
				this.queryParams.orderBy = column.order;
				this.queryParams.orderField = column.prop;
			}
			this.queryParams.page = 1;
			this.getData();
		},
		jumpInfo(row) {
			this.$router.push({
				name: 'userInfo',
				query: {
					id: row.id
				}
			});
		},
		getAdminAccount(admins) {
			const name = [];
			admins.forEach((item) => {
				name.push(item.account);
			});
			return name.join('、');
		},
		showUserDialog() {
			console.log(this.oneShippingAdminList);
			// this.userDialog = true;
			// this.dialogForm.account = '';
			// this.dialogForm.email = '';
			// this.dialogForm.password = '';
			// this.dialogForm.oneShippingAdminId = '';
			// this.dialogForm.middleTransferAdminId = '';
			// this.dialogForm.inboundSortingAdminId = '';

			if (this.oneShippingAdminList.length === 1) {
				this.dialogForm.oneShippingAdminId = this.oneShippingAdminList[0].adminId;
			}
			if (this.middleTransferAdminList.length === 1) {
				this.dialogForm.middleTransferAdminId = this.middleTransferAdminList[0].adminId;
			}
			if (this.inboundSortingAdminList.length === 1) {
				this.dialogForm.inboundSortingAdminId = this.inboundSortingAdminList[0].adminId;
			}
		}
	}
};
</script>

<style scoped lang="scss">
.wrap {
	margin-bottom: 50px;
	padding: 30px 30px;
	.header {
		display: flex;
		justify-content: space-between;
	}
	.content {
		width: 800px;
		padding: 20px 40px 0;
	}
}
.header-select {
	margin-right: 20px;
}
.form-tips {
	line-height: 20px;
	font-size: 12px;
}
/* 设置按钮样式 */
.footer {
	position: fixed;
	position: fixed;
	bottom: 0px;
	/* left: -20px; */
	color: white;
	padding: 10px 20px;
	border-top: 2px solid #dcdfe6;
	cursor: pointer;
	/* text-align: center; */
	text-decoration: none;
	display: inline-block;
	font-size: 16px;
	/* margin: 4px 2px; */
	-webkit-transition-duration: 0.4s;
	transition-duration: 0.4s;
	width: 100%;
	background-color: #ffffff;
}
</style>
